package com.clei.Y2021.M10.D20;

import com.clei.utils.Base64Util;

import javax.imageio.ImageIO;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.security.SecureRandom;
import java.util.Random;

/**
 * 图形验证码
 *
 * @author Y
 * @date 2021-10-20
 */
public class CaptchaTest {

    public static void main(String[] args) throws Exception {
        String captchaValue = getCaptchaValue();
        BufferedImage img = getCaptchaImg(captchaValue);
        String base64 = imgToBase64(img);
        String filePath = "E:\\tmp\\captcha.jpg";
        Base64Util.base64ToFile(base64, filePath);
    }

    /**
     * 验证码字符串
     *
     * @return 验证码字符串
     */
    private static String getCaptchaValue() {
        int length = 4;
        StringBuilder sb = new StringBuilder(length);
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            // 大小写混合
            int num = 'A' + random.nextInt(26);
            num = random.nextBoolean() ? num + 32 : num;
            sb.append((char) num);
        }
        return sb.toString();
    }

    /**
     * 图形验证码
     *
     * @param captchaValue 验证码字符串
     * @return BufferedImage BufferedImage
     */
    public static BufferedImage getCaptchaImg(String captchaValue) {
        int width = 95;
        int height = 30;
        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
        Graphics g = img.getGraphics();
        //1.画背景
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);
        //2.画字符串
        g.setColor(Color.BLACK);
        g.setFont(new Font("宋体", Font.BOLD, 32));

        for (int i = 0; i < captchaValue.toCharArray().length; i++) {
            char c = captchaValue.charAt(i);
            g.drawString(c + "", i * 20 + 8, 25);
        }
        SecureRandom random = new SecureRandom();
        g.setColor(Color.RED);
        for (int i = 0; i < 20; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int x2 = random.nextInt(width);
            int y2 = random.nextInt(height);
            g.drawLine(x, y, x + x2, y + y2);
        }
        return img;
    }

    /**
     * BufferedImage -> Base64字符串
     *
     * @param image image
     * @return base64字符串
     * @throws Exception Exception
     */
    private static String imgToBase64(BufferedImage image) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "PNG", outputStream);
        String base64Img = Base64Util.encode(outputStream.toByteArray())
                .replaceAll("\n", "")
                .replaceAll("\r", "");
        outputStream.close();
        return base64Img;
    }
}